<template>
  <div>
    <el-card class="card" style="max-width: 1200px">
      <div>
        <div class="flex justify-between">
          <div class="mb-10px flex gap-10px">
            <div class="flex items-center">
              <span>章节号：</span>
              <el-input
                v-model="selectedSectionId"
                placeholder="请输入章节号"
                style="width: 150px; margin-left: 10px"
                type="number"
                :min="1"
                @change="getCourseList"
              />
            </div>
          </div>
          <div class="btn-area">
            <el-button :icon="RefreshRight" style="margin-left: 10px" @click="getCourseList">
              刷新
            </el-button>
            <el-button type="primary" @click="addCourse">新增</el-button>
          </div>
        </div>
        <el-table
          :data="courseList"
          border
          style="width: 100%"
          :cell-style="{ whiteSpace: 'nowrap' }"
        >
          <el-table-column prop="sectionName" label="章节名称" />
          <el-table-column prop="knowPointId" label="知识点" />
          <el-table-column prop="sectionName" label="知识点名称" />
          <el-table-column prop="describes" label="知识点描述" />
          <el-table-column prop="summary" label="知识点总结" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleUpdateCourse(scope.row)">
                修改
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteCourse(scope.row.sectionId, scope.row.knowPointId)"
              >
                删除
              </el-button>
              <el-upload
                class="handle"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button type="primary" size="small">上传</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 创建课程对话框 -->
      <el-dialog
        v-model="dialogVisible1"
        :title="courseInfo + '课程'"
        width="500"
        :before-close="handleClose"
      >
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="章节" prop="sectionId">
            <el-input v-model="ruleForm.sectionId" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="知识点号" prop="knowPointId">
            <el-input v-model="ruleForm.knowPointId" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="章节名称" prop="sectionName">
            <el-input v-model="ruleForm.sectionName" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="知识点名" prop="class">
            <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="ruleForm.description" type="textarea" autocomplete="off" />
          </el-form-item>
          <el-form-item label="总结" prop="summary">
            <el-input v-model="ruleForm.summary" type="textarea" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, UploadProps } from "element-plus";
import {
  addKnowPointInfo,
  courseManage,
  ICourse,
  removeKnowPoint,
  updateKnowPointInfo,
} from "@/api/subject";
import { RefreshRight } from "@element-plus/icons-vue";
// 原始 JSON 数据
// const jsonData = ref({
//   title:
//     '以下C语言代码段用于判断一个年份是否为闰年，请在横线处填入正确的代码，使程序能够正常运行并输出正确结果。\\n```c\\n#include <stdio.h>\\nint main() {\\n    int year;\\n    printf(\\"请输入一个年份: \\");\\n    scanf(\\"%d\\", &year);\\n    if ((______ % 4 == 0 && ______ % 100 != 0) || ______ % 400 == 0) {\\n        printf(\\"%d 是闰年\\\\n\\", year);\\n    } else {\\n        printf(\\"%d 不是闰年\\\\n\\", year);\\n    }\\n    return 0;\\n}\\n```',
//   answer: ["year", "year", "year"],
//   analysis:
//     "判断一个年份是否为闰年，可以通过以下条件：年份能被4整除且不能被100整除，或者能被400整除。`year % 4 == 0 && year % 100 != 0`表示年份能被4整除但不能被100整除，`year % 400 == 0`表示年份能被400整除。",
//   hierarchy: 4,
//   difficulty: 3,
//   coefficient: 1,
//   referenceTime: 10,
// });

const selectedSectionId = ref<number>(1);
// 模拟课程数据
const courseList = ref<ICourse[]>();
// 获取知识点数据
const getCourseList = async () => {
  courseList.value = await courseManage({ sectionId: selectedSectionId.value });
};

onMounted(() => getCourseList());
const ruleFormRef = ref();
const courseInfo = ref("修改");
const dialogVisible1 = ref(false);
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("是否要关闭?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
interface course {
  id: string;
  name: string;
  description: string;
  summary: string;
  sectionId: number;
  sectionName: string;
  knowPointId: null;
}
let currentRow = {
  id: 1,
  name: "",
  description: "",
  summary: "",
  sectionId: 1,
  sectionName: "",
  knowPointId: 1,
};
// 上传逻辑
// const uploadRef = ref<UploadInstance>();
// const handleUpload = async (data: any) => {
//   const fromData = new FormData();
//   fromData.set("file", data.file);
//   console.log(data);
//   await uploadPoint(fromData);
//   uploadRef.value?.clearFiles();
//   ElMessage.success("上传成功");
// };
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 1, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile) => {
  return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};

const submitForm = () => {
  //合法性判断
  ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (courseInfo.value === "新增") {
        dialogVisible1.value = false;
        openDialog(true);
        const query = {
          sectionId: Number(ruleForm.value.sectionId),
          sectionName: ruleForm.value.sectionName,
          knowPointId: Number(ruleForm.value.knowPointId),
          knowPointName: ruleForm.value.name,
          describes: ruleForm.value.description,
          summary: ruleForm.value.summary,
        };
        await addKnowPointInfo(query);
        ElMessage.success("新增成功");
        dialogVisible1.value = false;
        getCourseList();
      } else {
        await updateCourse(ruleForm);
        ElMessage.success("修改成功");
        getCourseList();
        dialogVisible1.value = false;
      }
    } else {
      ElMessage.error("填写内容不合法");
    }
  });
};
const resetForm = () => {
  dialogVisible1.value = false;
};
const rules = {
  sectionId: [{ required: true, message: "请输入章节号", trigger: "blur" }],
  knowPointId: [{ required: true, message: "请输入知识点号", trigger: "blur" }],
  name: [{ required: true, message: "请输入知识点名称", trigger: "blur" }],
  description: [{ message: "请输入课程描述", trigger: "blur" }],
  summary: [{ message: "请输入知识点描述", trigger: "blur" }],
};
const openDialog = (isAdd: boolean) => {
  if (isAdd) {
    courseInfo.value = "新增";
  } else {
    courseInfo.value = "修改";
  }
  dialogVisible1.value = true;
};

const ruleForm = ref({
  id: "1",
  sectionId: 1,
  sectionName: "",
  knowPointId: null,
  name: "",
  description: "",
  summary: "",
});

const handleUpdateCourse = (row: any) => {
  ruleForm.value.sectionId = row.sectionId;
  ruleForm.value.knowPointId = row.knowPointId;
  ruleForm.value.name = row.knowPointName;
  ruleForm.value.description = row.describes;
  ruleForm.value.summary = row.summary;
  ruleForm.value.sectionName = row.sectionName;
  openDialog(false);
  console.log(ruleForm.value);
};
// 修改课程
const updateCourse = async (row: course) => {
  Object.assign(currentRow, row);
  const data = {
    sectionId: ruleForm.value.sectionId,
    sectionName: ruleForm.value.sectionName,
    knowPointId: ruleForm.value.knowPointId,
    knowPointName: ruleForm.value.name,
    describes: ruleForm.value.description,
    summary: ruleForm.value.summary,
  };
  await updateKnowPointInfo(data);
  openDialog(false);
};
const addCourse = () => {
  ruleForm.value = {
    id: "1",
    sectionId: selectedSectionId.value || 1,
    sectionName: "",
    knowPointId: null,
    name: "",
    description: "",
    summary: "",
  };
  openDialog(true); // 打开对话框
};
// const handleAddCourse = async (data: any) => {
//   openDialog(true);
//   const query = {
//     sectionId: Number(ruleForm.value.sectionId),
//     sectionName: ruleForm.value.sectionName,
//     knowPointId: Number(ruleForm.value.knowPointId),
//     knowPointName: ruleForm.value.name,
//     describes: ruleForm.value.description,
//     summary: ruleForm.value.summary,
//   };
//   await addKnowPointInfo(query);
//   ElMessage.success("新增成功");
// };
// 添加课程

// 删除课程
const deleteCourse = async (sectionId: string, knowPointId: string) => {
  await ElMessageBox.confirm("确定删除?");
  await removeKnowPoint({ sectionId, knowPointId });
  ElMessage.success("删除成功");
  await getCourseList();
};
</script>

<style scoped>
.card {
  margin: 20px;
}
.btn-area {
  margin-bottom: 10px;
  float: right;
}
.el-button {
  margin-left: 0;
  margin-right: 5px;
}
.handle {
  display: inline-block;
  width: 30%;
  margin: 3px;
}
:deep(.el-table__inner-wrapper table) {
  table-layout: fixed;
  width: 100%;
}
.el-table__header,
.el-table__body {
  table-layout: fixed;
}

.el-table th,
.el-table td {
  width: 16.66%; /* 对于六列来说 */
}
</style>
